package com.studyjava.guessdx;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Objects;
import java.util.Random;

public class help extends AppCompatActivity implements SensorEventListener {

    private SensorManager sensorManager;
    private Sensor accelerometer;
    private MediaPlayer shakeMediaPlayer;
    private MediaPlayer backgroundMediaPlayer;
    private static final float SHAKE_THRESHOLD = 15.0f; // 定义晃动的阈值
    private static final int TIME_THRESHOLD = 1000; // 限制播放的时间间隔
    private long lastShakeTime = 0;
    private int shakeCount = 0;
    private int userScore;

    // UI 元素
    private TextView shakeCountTextView;
    private TextView currentAudioTextView;
    private Spinner backgroundMusicSpinner;
    private Spinner shakeSoundSpinner;
    private ImageView backgroundImageView;
    private Random random = new Random();

    private String[] backgroundMusicOptions = {"erin_new_00", "erin_miku_00", "erin_old_00"};
    private String[] shakeSoundOptions = {"erin_new_01", "erin_miku_01", "erin_old_01"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.helpailin);

        //初始化userscore
        loadUserScore();

        // 初始化传感器管理器和加速度传感器
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null) {
            accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        }

        // 初始化摇动次数 TextView
        shakeCountTextView = findViewById(R.id.shakeCountTextView);
        currentAudioTextView = findViewById(R.id.currentAudioTextView);
        backgroundMusicSpinner = findViewById(R.id.backgroundMusicSpinner);
        shakeSoundSpinner = findViewById(R.id.shakeSoundSpinner);
        backgroundImageView = findViewById(R.id.backgroundImageView);

        // 设置背景音乐选择 Spinner
        ArrayAdapter<String> backgroundMusicAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, backgroundMusicOptions);
        backgroundMusicAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        backgroundMusicSpinner.setAdapter(backgroundMusicAdapter);

        // 设置提示音选择 Spinner
        ArrayAdapter<String> shakeSoundAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, shakeSoundOptions);
        shakeSoundAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        shakeSoundSpinner.setAdapter(shakeSoundAdapter);

        // 监听背景音乐选择
        backgroundMusicSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedMusic = backgroundMusicOptions[position];
                playBackgroundMusic(selectedMusic);
                updateBackgroundImage(selectedMusic);
                updateCurrentAudioText();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        // 监听提示音选择
        shakeSoundSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedShakeSound = shakeSoundOptions[position];
                setShakeSound(selectedShakeSound);
                updateCurrentAudioText();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        // 初始化背景音乐和提示音
        playBackgroundMusic("erin_new_00");
        setShakeSound("erin_new_01");
        updateBackgroundImage("erin_new_00");
    }

    private void playBackgroundMusic(String musicName) {
        if (backgroundMediaPlayer != null) {
            backgroundMediaPlayer.stop();
            backgroundMediaPlayer.release();
        }

        int resId = getResources().getIdentifier(musicName, "raw", getPackageName());
        backgroundMediaPlayer = MediaPlayer.create(this, resId);
        backgroundMediaPlayer.setLooping(true);
        backgroundMediaPlayer.start();
    }

    private void setShakeSound(String soundName) {
        if (shakeMediaPlayer != null) {
            shakeMediaPlayer.release();
        }

        int resId = getResources().getIdentifier(soundName, "raw", getPackageName());
        shakeMediaPlayer = MediaPlayer.create(this, resId);
    }

    private void updateBackgroundImage(String musicName) {
        int resId = getResources().getIdentifier(musicName, "drawable", getPackageName());
        backgroundImageView.setImageResource(resId);
    }

    private void updateCurrentAudioText() {
        String currentBackgroundMusic = backgroundMusicOptions[backgroundMusicSpinner.getSelectedItemPosition()];
        String currentShakeSound = shakeSoundOptions[shakeSoundSpinner.getSelectedItemPosition()];
        String cn_bg = "";
        String cn_ss = "";

        if (Objects.equals(currentBackgroundMusic, "erin_new_00")){
            cn_bg = "重制版";
        }
        if (Objects.equals(currentBackgroundMusic, "erin_miku_00")){
            cn_bg = "初音版";
        };
        if (Objects.equals(currentBackgroundMusic, "erin_old_00")){
            cn_bg = "经典版";
        }


        if (Objects.equals(currentShakeSound, "erin_new_01")){
            cn_ss = "重制版";
        }
        if (Objects.equals(currentShakeSound, "erin_miku_01")){
            cn_ss = "初音版";
        };
        if (Objects.equals(currentShakeSound, "erin_old_01")){
            cn_ss = "经典版";
        }
        currentAudioTextView.setText("背景音乐: " + cn_bg + ", 提示音: " + cn_ss);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 注册加速度传感器监听
        if (accelerometer != null) {
            sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 注销传感器监听
        sensorManager.unregisterListener(this);
        if (backgroundMediaPlayer != null) {
            backgroundMediaPlayer.pause();
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            float acceleration = (float) Math.sqrt(x * x + y * y + z * z) - SensorManager.GRAVITY_EARTH;

            long currentTime = System.currentTimeMillis();

            if (acceleration > SHAKE_THRESHOLD && (currentTime - lastShakeTime) > TIME_THRESHOLD) {
                lastShakeTime = currentTime;
                shakeCount++;
                shakeCountTextView.setText(String.valueOf(shakeCount));
                playShakeSound(); // 播放提示音

                if (userScore<100){
                    userScore = 100;
                    saveUserScore();
                }else{
                    incrementUserScore();
                }

            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    private void playShakeSound() {
        if (shakeMediaPlayer != null) {
            shakeMediaPlayer.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (shakeMediaPlayer != null) {
            shakeMediaPlayer.release();
            shakeMediaPlayer = null;
        }
        if (backgroundMediaPlayer != null) {
            backgroundMediaPlayer.release();
            backgroundMediaPlayer = null;
        }
    }

    //积分相关

    //读取积分
    private void loadUserScore() {
        try {
            InputStream inputStream = openFileInput("userdata.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = parser.getName();
                if (eventType == XmlPullParser.START_TAG && "Score".equals(tagName)) {
                    userScore = Integer.parseInt(parser.nextText());
                }
                eventType = parser.next();
            }
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 保存用户积分到文件中
    private void saveUserScore() {
        try {
            FileOutputStream fileOutputStream = openFileOutput("userdata.xml", MODE_PRIVATE);
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fileOutputStream, "UTF-8");

            serializer.startDocument("UTF-8", true);
            serializer.startTag(null, "UserData");
            serializer.startTag(null, "Score");
            serializer.text(String.valueOf(userScore));
            serializer.endTag(null, "Score");
            serializer.endTag(null, "UserData");
            serializer.endDocument();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void incrementUserScore() {
        // 生成1到20的随机数
        int randomValue = random.nextInt(20) + 1;  // nextInt(20) 生成0-19, 加1得到1-20

        // 0.3%的概率增加1000分
        if (random.nextDouble() < 0.003) {  // nextDouble() 生成0到1之间的随机小数
            randomValue += 1000;
        }

        // 将随机数加到userScore
        userScore += randomValue;

        saveUserScore();
    }
}
